﻿

using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using ZFBActivation.Log;

namespace ZFBActivation.Core
{
	public static class SettingHelper
	{

		/// <summary>
		/// </summary>
		public static AppSetting SysSetting { get; set; } = new AppSetting();

	
		private static readonly object lockObj = new object();

		/// <summary>
		///     保存配置
		/// </summary>
		public static void Sava() {
			lock (lockObj) {
				try {
					var json = new {
						SysSetting,
					};

					var str = System.Text.Json.JsonSerializer.Serialize(json);

					var filePath = Path.Combine(Environment.CurrentDirectory, "Setting.json");
					File.WriteAllText(filePath, str, Encoding.UTF8);
				} catch (Exception ex) {
					LogHelper.Log(LogDefine.LogError, ex, "保存配置文件失败");
				}
			}
		}


		public static bool Load() {


			var filePath = Path.Combine(Environment.CurrentDirectory, "Setting.json");
			if (File.Exists(filePath)) {
				var content = File.ReadAllText(filePath, Encoding.UTF8);
				try {
					var tmp = System.Text.Json.JsonSerializer.Deserialize<JsonObject>(content);

                    SysSetting = JsonSerializer.Deserialize<AppSetting>(tmp["SysSetting"]);

                    if (SysSetting == null) {
                        SysSetting = new AppSetting();
                    }
				
					Sava();
				} catch (Exception ex) {
					LogHelper.Log(LogDefine.LogError, ex, $"配置文件载入异常:{filePath},{content}");
					return false;
				}
			} else {
				Sava();
				return Load();
			}
			return true;
		}
	}


	public class AppSetting
    {
		public string QueryPwd { get; set; }

		public string PayPwd { get; set; }
		public int RunMax { get; set; }

		public string ProxyUrl { get; set;}
		public string BrowserPath { get; set;}
    }
}